from rest_framework import generics
from ..models import Subject,Course
from .serializers import SubjectSerializer
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import detail_route
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated

class SubjectListView(generics.ListAPIView):
	queryset = Subject.objects.all()
	serializer_class = SubjectSerializer

class SubjectDetailView(generics.RetrieveAPIView):
	queryset = Subject.objects.all()
	serializer_class = SubjectSerializer
# rest_framework 提供一个APIView类，这个类基于Django 的View类构建API功能，APIView类与View在使用
#Rest Framework的定制Request和Response对象时不同，并操作APIException例外的返回合适的HTTP响应
class CourseEnrollView(APIView):
	def post(self,request,pk,format=None):
		course = get_object_or_404(Course,pk=pk)
		course.students.add(request.user)
		return Response({'enrolled':True})

class CourseViewSet(viewsets.ReadOnlyModelViewSet):
	queryset = Course.objects.all()
	serializer_class = CourseSerializer
	#装饰器只允许post方法，并设置认证，权限类
	@detail_route(method=['post'],authentication_class=['BasicAuthentication'],permissions_class=[IsAuthenticated])
	def enroll(self,request,*args,**kwargs):
		course = self.get_object() #获取Course对象
		course.students.add(request.user)
		return Response({'enrolled':True})
	